<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      </el-row>
      <el-row>
        <el-steps align-center :space="200" :active="activeIndex-0" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-row>
      <el-row>
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-position="top"
          label-width="100px"
        >
          <el-tabs
            v-model="activeIndex"
            tab-position="left"
            :before-leave="beforeTabLeave"
            @tab-click="tabClick"
          >
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input type="number" v-model="addForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input type="number" v-model="addForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input type="number" v-model="addForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props="cascaderProps"
                  @change="cateChange"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>

            <!-- 商品参数 -->
            <el-tab-pane label="商品参数" name="1">
              <el-form-item
                :label="item.attr_name"
                v-for="item in manyTableData"
                :key="item.attr_id"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox border :key="i" v-for="(cb,i) in item.attr_vals" :label="cb"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>

            <!-- 商品属性 -->
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                :label="item.attr_name"
                v-for="item in onlyTableData"
                :key="item.attr_id"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>

            <!-- 商品图片 -->
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                :action="uploadURL"
                :on-success="handleSuccess"
                :headers="headersObj"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-tab-pane>

            <!-- 商品内容 -->
            <el-tab-pane label="商品内容" name="4">
              <quill-editor v-model="addForm.goods_introduce"></quill-editor>
              <el-button class="addButton" type="primary" @click="addGoods">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-row>
    </el-card>

    <!-- 弹出式预览框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <span>
        <img class="preview-img" :src="previewFile" :alt="'图片预览'+previewFile" />
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data () {
    return {
      activeIndex: '0',
      // 添加商品的表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单验证
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', message: '请输入正确数据', trigger: 'blur', transform: (value) => Number(value) },
          { pattern: /^([1-9]|[1-9]d|1dd|2[0-4]d|25[0-5])$/, message: '范围在1-255', trigger: 'blur' }
          /*
              范围1-255分析：
              1-9：      [1-9]
              10-99：    [1-9]d
              100-199:   1dd
              200-249:   2[0-4]d
              250-255:   25[0-5]
            */
        ],
        goods_number: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', message: '请输入正确数据', trigger: 'blur', transform: (value) => Number(value) },
          { pattern: /^([1-9]|[1-9]d|1dd|2[0-4]d|25[0-5])$/, message: '范围在1-255', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入重量', trigger: 'blur' },
          { type: 'number', message: '请输入正确数据', trigger: 'blur', transform: (value) => Number(value) },
          { pattern: /^([1-9]|[1-9]d|1dd|2[0-4]d|25[0-5])$/, message: '范围在1-255', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择类别', trigger: 'blur' }
        ]
      },
      // 存储数据列表
      cateList: [],
      // 多级列表中的参数
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: 'true'
      },
      // 动态参数列表
      manyTableData: [],
      // 属性列表数据
      onlyTableData: [],
      uploadURL: 'http://timemeetyou.com:8889/api/private/v1/upload',
      // 图片上传组件的headers请求头对象
      headersObj: { Authorization: window.sessionStorage.getItem('token') },
      previewDialogVisible: false,
      previewFile: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类信息
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类信息失败！')
      // this.$message.success(res.meta.msg)
      this.cateList = res.data
    },
    cateChange () {
      console.log(this.addForm.goods_cat.join(','))
    },
    beforeTabLeave (activeName, oldActiveName) {
      // console.log(this.addForm.goods_cat.length)
      console.log(activeName, oldActiveName)
      // 若是从第一个页签切换出去，并且没有选择分类就报错并阻止切换
      if (oldActiveName === '0' && this.addForm.goods_cat.length === 0) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    async tabClick () {
      console.log('this.activeIndex=>' + this.activeIndex)
      if (this.activeIndex === '1') {
        console.log('this.activeIndex=>' + this.activeIndex)
        console.log('this.addForm.goods_cat.slice(-1)=>' + this.addForm.goods_cat.slice(-1))
        const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat.slice(-1)}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数错误！')

        // 在赋值之前修改字符串为数组
        res.data.forEach(
          item => {
            if (item.attr_vals.length === 0) {
              item.attr_vals = []
            } else {
              item.attr_vals = item.attr_vals.split(',')
            }
          }
        )
        console.log(res.data)
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat.slice(-1)}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数错误！')
        this.onlyTableData = res.data
      }
    },
    // 图片预览事件函数
    handlePreview (file) {
      console.log(file)
      this.previewFile = file.response.data.url
      this.previewDialogVisible = true
    },
    // 图片移除事件函数
    handleRemove (file) {
      // 获取将要删除图片路径
      const filePath = file.response.data.tmp_path
      // 从pics数组中找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      // 调用数组splice方法删除图片对象
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 监听图片上传成功的事件
    handleSuccess (response) {
      // 1、拼接得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // 2、将图片信息对象push到pics数组中
      this.addForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods () {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return this.$message.error('请填写必要的表单项！')

        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')

        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join(',')
          }
          this.addForm.attrs.push(newInfo)
        })

        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })

        form.attrs = this.addForm.attrs

        console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        console.log('res=>', res)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0;
}
.preview-img {
  width: 100%;
}
.addButton {
  margin-top: 10px;
}
</style>
